<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\model\CourseList;
use app\common\model\ExperienceCourseList;
use app\common\model\Feedback;
use app\common\model\GroupWork;
use app\common\model\Order;
use app\common\model\TuanCourseList;
use app\common\model\User as userModel;
use fast\Random;
use think\Validate;
use think\Db;

/**
 * 会员接口
 */
class User extends Api
{
    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 会员中心
     * @param string $token TOKEN
     * @ApiReturn   ({
    "code": 200,
    "msg": "请求成功",
    "time": "1597391545",
    "data": {
    "id": 1,
    "username": "admin",用户昵称
    "head_image": "\/assets\/img\/avatar.png",头像
    "group_id": 3,1普通会员2商家3代理商4商家、代理商
    "status_text": ""
    }
    })
     */
    public function index()
    {
        $token = $this->request->get('token');
        $user_info = userModel::where('token',$token)->field('id,username,avatar')->find();
        $this->success($user_info);
    }

    /**
     * 绑定手机号
     * @ApiMethod   (POST)
     * @param string $token  用户token
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function bindmobile()
    {
        $token = $this->request->post('token');
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        $user_info = userModel::where('token',$token)->field('id')->find();
        if(!$mobile){
            $this->error('请输入手机号');
        }
        if(!$captcha){
            $this->error('请输入验证码');
        }
        $user = userModel::getByMobile($mobile);
        if($user){
            $this->error('该手机号已被绑定');
        }
        if (!Sms::check($mobile, $captcha, 'bindmobile')) {
            $this->error(__('Captcha is incorrect'));
        }
        Db::startTrans();
        try {
            $res = userModel::where('id',$user_info['id'])->update(['mobile'=>$mobile]);
            Db::commit();
        } catch (Exception $e) {
            $this->error($e->getMessage());
            Db::rollback();
            return false;
        }
        if($res){
            $this->success('');
            if(session('url')){
                $location_url = session('url');
                session('url',null);
                header('location:'.$location_url);
                exit;
            }else{
                header('location:'.$this->domain);exit;
            }
        }else{
            $this->error('绑定失败');
        }
    }
    /**
     * 意见反馈提交
     * @ApiMethod   (POST)
     * @param string $token TOKEN
     * @param int $content 反馈内容
     * @param int $images 反馈图片
     */
    public function  sumbit_feedback()
    {
        $token = $this->request->post('token');
        $content = $this->request->post('content');
        $images = $this->request->post('images');
        $user_info = userModel::where('token',$token)->field('id')->find();
        if(!$content && !$images){
            $this->error(__('请填写内容'));
        }
        $data = [
            'content'=>$content,
            'images'=>$images,
            'userid'=>$user_info['id']
        ];
        Db::startTrans();
        try {
            $res = Feedback::create($data);
            Db::commit();
        } catch (Exception $e) {
            $this->error($e->getMessage());
            Db::rollback();
            return false;
        }
        if($res){
            $this->success('',__('提交成功'));
        }else{
            $this->error(__('提交失败'));
        }
    }
    /**
     * 获取userid
     * @param string $token TOKEN
     * @ApiReturn   ({
    "code": 200,
    "msg": "请求成功",
    "time": "1597716431",
    "data": {
    "id": "1",userid
    }
    })
     */
    public function user_info()
    {
        $token = $this->request->get('token');
        $user_info = userModel::where('token',$token)->field('id')->find();
        $this->success($user_info);
    }
    /**
     * 获取微信config
     * @param string url 当前url
     * @param string $token TOKEN
     * @ApiReturn   ()
     */
    public function get_config(){
        $token = $this->request->get('token') ;
        $url = urldecode($this->request->get('url')) ;
        $data = getConfig($url);
        $this->success($data);
    }
    /**
     * 我的奖励课程
     * @param string $token TOKEN
     * @ApiReturn   ({
    "code": 200,
    "msg": "请求成功",
    "time": "1610953532",
    "data": [{
    "id": 3,
    "userid": 1,
    "name": "课程大礼包",
    "createtime": "2021-01-18"
    }]
    })
     */
    public function my_giveaway()
    {
        $token = $this->request->get('token');
        $user_info = userModel::where('token',$token)->field('id')->find();
        $list = Db::name('giveaway_list')->where('userid',$user_info['id'])->order('id desc')->select();
        foreach($list as &$value){
            $value['createtime'] = date('Y-m-d',$value['createtime']);
        }
        $this->success($list);
    }
    /**
     * 订单列表
     * @param string $token TOKEN
     * @param int $type 0待支付1已支付
     * @param int $page 页数，默认为1
     * @ApiReturn   ({
    "code": 200,
    "msg": "请求成功",
    "time": "1611145223",
    "data": [{
    "id": 6,订单ID
    "order_sn": "A1186008283941",订单号
    "status": 1,状态:0=待付款,1=已付款,2=已退款
    "type": 1,类型:0=普通课程,1=拼团课程,2=体验课程
    "price": "200.00",价格
    "group_work_id": 3,
    "kecheng_id": 1,
    "tuan_status": 2,拼团状态:0=待成团,1=拼团中,2=拼团成功,3=拼团失败
    "name": "2人拼团大礼包",课程名称
    "image": "\/uploads\/20210120\/9708b999a265c96803c308e786fb131a.jpg",课程图片
    "status_text": "Status 1",
    "paytime_text": "",
    "type_text": "Type 1"
    }, {
    "id": 5,
    "order_sn": "A1186008283944",
    "status": 1,
    "type": 1,
    "price": "200.00",
    "group_work_id": 3,
    "kecheng_id": 1,
    "tuan_status": 2,
    "name": "2人拼团大礼包",
    "image": "\/uploads\/20210120\/9708b999a265c96803c308e786fb131a.jpg",
    "status_text": "Status 1",
    "paytime_text": "",
    "type_text": "Type 1"
    }, {
    "id": 2,
    "order_sn": "A1185316357928",
    "status": 1,
    "type": 0,
    "price": "300.00",
    "group_work_id": 0,
    "kecheng_id": 1,
    "apply_refund": 0未申请退款1已申请退款,
    "name": "基础纯英班（1-3个人）",
    "image": "\/uploads\/20210120\/9708b999a265c96803c308e786fb131a.jpg",
    "status_text": "Status 1",
    "paytime_text": "",
    "type_text": "Type 0"
    }]
    })
     */
    public function order_list()
    {
        $token = $this->request->get('token');
        $type = $this->request->get('type');
        $user_info = userModel::where('token',$token)->field('id')->find();
        $pagesize = 10;
        $page = $this->request->get('page') == null ? 1 : $this->request->get('page');
        $page = ($page - 1) * $pagesize;
        $list = Order::where('userid',$user_info['id'])->where('status',$type)->field('id,order_sn,status,type,price,group_work_id,kecheng_id,apply_refund')->limit($page,$pagesize)->order('id desc')->select();
        foreach($list as &$value){
            if($value['type'] == 0){
                $goods_info = CourseList::where('id',$value['kecheng_id'])->field('name,images')->find();
            }elseif($value['type'] == 1){
                $goods_info = TuanCourseList::where('id',$value['kecheng_id'])->field('name,images')->find();
                $group_work = GroupWork::where('id',$value['group_work_id'])->find();
                if($group_work){
                    $value['tuan_status'] = $group_work['status'];
                }
            }elseif($value['type'] == 2){
                $goods_info = ExperienceCourseList::where('id',$value['kecheng_id'])->field('name,images')->find();
            }
            if($goods_info){
                $value['name'] = $goods_info['name'];
                $images = explode(',',$goods_info['images']);
                $value['image'] = $this->domain.$images[0];
            }
        }
        $this->success($list);
    }
    /**
     * 订单详情
     * @param string $token TOKEN
     * @param int $id 订单ID
     * @ApiReturn   ({
    "code": 200,
    "msg": "请求成功",
    "time": "1611146054",
    "data": {
    "id": 5,订单ID
    "order_sn": "A1186008283944",订单号
    "kecheng_id": 1,
    "apply_refund": 0未申请退款1已申请退款,
    "userid": 1,
    "price": "200.00",价格
    "status": 1,状态:0=待付款,1=已付款,2=已退款
    "paytime": 1611144384,支付时间
    "type": 1,类型:0=普通课程,1=拼团课程,2=体验课程
    "group_work_id": 3,
    "createtime": 1610960083,创建时间
    "share_id": 0,
    "tuan_status": 2,拼团状态:0=待成团,1=拼团中,2=拼团成功,3=拼团失败
    "name": "2人拼团大礼包",课程名称
    "image": "\/uploads\/20210120\/9708b999a265c96803c308e786fb131a.jpg",课程图片
    "status_text": "Status 1",
    "paytime_text": "2021-01-20 20:06:24",
    "type_text": "Type 1"
    }
    })
     */
    public function order_detail()
    {
        $token = $this->request->get('token');
        $id = $this->request->get('id');
        $user_info = userModel::where('token',$token)->field('id')->find();
        $info = Order::where(['id'=>$id,'userid'=>$user_info['id']])->find();
        if($info){
            $info['createtime'] = date('Y-m-d H:i',$info['createtime']);
            $info['paytime'] = date('Y-m-d H:i',$info['paytime']);
            if($info['type'] == 0){
                $goods_info = CourseList::where('id',$info['kecheng_id'])->field('name,images,class')->find();
            }elseif($info['type'] == 1){
                $goods_info = TuanCourseList::where('id',$info['kecheng_id'])->field('name,images,class')->find();
                $group_work = GroupWork::where('id',$info['group_work_id'])->find();
                if($group_work){
                    $info['tuan_status'] = $group_work['status'];
                }
            }elseif($info['type'] == 2){
                $goods_info = ExperienceCourseList::where('id',$info['kecheng_id'])->field('name,images,class')->find();
            }
            if($goods_info){
                $info['name'] = $goods_info['name'];
                $images = explode(',',$goods_info['images']);
                $info['image'] = $this->domain.$images[0];
            }
            $this->success($info);
        }
        $this->error('暂无数据');
    }
    /**
     * 取消订单
     * @param string $token TOKEN
     * @param string $order_id 订单ID
     * @ApiReturn   ()
     */
    public function cancel_order()
    {
        $token = $this->request->get('token');
        $order_id = $this->request->get('order_id');
        $user= userModel::where('token',$token)->field('id')->find();
        $info = Order::where('id',$order_id)->where('userid',$user['id'])->find();
        if($info){
            if($info['status'] != 0){
                $this->error('只有未支付的订单才可取消');
            }
            $res = Order::where('id',$order_id)->where('userid',$user['id'])->delete();
            $this->success('','取消成功');
        }
        $this->error('订单不存在');
    }
    /**
     * 立即支付
     * @ApiMethod   (POST)
     * @param string $token 用户token
     * @param string $order_id 订单ID
     * @ApiReturn   ()
     */
    public function pay_immediately()
    {
        $token = $this->request->post('token');
        $order_id = $this->request->post('order_id');
        $user= userModel::where('token',$token)->field('id,openid')->find();
        $info = Order::where('id',$order_id)->where('userid',$user['id'])->find();
        if($info){
            if($info['status'] != 0){
                $this->error('只有未支付的订单才可支付');
            }
            //优惠券
            $data['order_sn'] = getOrderSn();
            Db::startTrans();
            try {
                $res = Order::where('id',$info['id'])->update($data);
                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if($res){
                $out_trade_no = $data['order_sn'];
                $amount =$info['price'];
                $jsapi = new Response();
                $result = $jsapi->wx_pay($out_trade_no, $amount, $user['openid']);
                $result = json_decode($result,true);
                $this->success($result,'请求成功');
            }
            $this->success('','取消成功');
        }
        $this->error('订单不存在');
    }
    /**
     * 申请退款
     * @ApiMethod   (POST)
     * @param string $token 用户token
     * @param string $order_id 订单ID
     * @ApiReturn   ()
     */
    public function allpy_refund()
    {
        $token = $this->request->post('token');
        $order_id = $this->request->post('order_id');
        $user= userModel::where('token',$token)->field('id,openid')->find();
        $info = Order::where('id',$order_id)->where('userid',$user['id'])->find();
        if($info){
            if($info['status'] != 1){
                $this->error('该订单不能申请退款');
            }
            if(($info['paytime']+86400*3) <time()){
                $this->error('该订单支付已经超过3天，不能申请退款');
            }
            if($info['apply_refund'] == 1){
                $this->error('正在申请中。。。');
            }
            $res = Order::where('id',$order_id)->where('userid',$user['id'])->update(['apply_refund'=>1]);
            $this->success('','申请成功，等待审核');
        }
        $this->error('订单不存在');
    }
}
